/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.absisgroup.nsc.utilities;

import com.absisgroup.nsc.users.UsersEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.HttpJspPage;
import org.apache.struts.util.MessageResources;
import org.json.JSONObject;

/**
 *
 * @author Hue
 */
public class GenericServlet extends HttpServlet implements HttpJspPage, Constants {
    
    public GenericServlet() {
        
    }

    @Override
    public final void init(final ServletConfig config) throws ServletException {
        super.init(config);
        jspInit();
        _jspInit();
    }

    @Override
    public final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
        process(request, response);
    }
    
    @Override
    public final void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
        process(request, response);
    }
    
    private void process(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        Throwable exception = null;
        Connection con = null;
        String sqlLogfile;
        try {
            if(useConnection()) {
                sqlLogfile = getLogFile(request);
                con = DBUtilities.getConnection(getServletContext(), sqlLogfile);
            }
            final int iReturn = process(con, request, response);
            DBUtilities.closeConnection(con);

            if(iReturn == RUN_JSP) {
                //display JSP page [
                try {
                    _jspService(request,response);
                }
                catch(Exception ex) {
                    if(ex instanceof ServletException && ((ServletException)ex).getRootCause() != null) {
                        throw ((ServletException)ex).getRootCause();
                    }
                    else {
                        throw ex;
                    }
                }
                //]
            }
        }
        catch(Throwable ex) {
            exception = ex;
        }
        finally {
            DBUtilities.closeConnection(con);
            if(exception != null) {
                showException(response, exception);
            }
        }
        try {
            response.flushBuffer();
        }
        catch(java.io.IOException ex) {
            //do nothing
        }
    }
    
    /* @return RUN_JSP or DONT_RUN_JSP */
    public int process(final Connection con, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        return RUN_JSP;
    }
    
    protected boolean isLogon(final HttpServletRequest request) {
        return (getCurrentUser(request) != null);
    }
    
    public UsersEntity getCurrentUser(final HttpServletRequest request) {
        return getCurrentUser(request.getSession());
    }
    
    protected UsersEntity getCurrentUser(final HttpSession session) {
        return ((UsersEntity)session.getAttribute(USER_KEY));
    }

    protected void showException(final HttpServletResponse response, final Throwable ex) {
        log("showException", ex);
        System.out.println(ex);
        try {
            final JSONObject jsObj = new JSONObject();
            jsObj.put("success", false);
            final ByteArrayOutputStream baOut = new ByteArrayOutputStream();
            final PrintWriter pw = new PrintWriter(baOut);
            ex.printStackTrace(pw);
            pw.flush();
            final String msg = baOut.toString();
            baOut.close();
            pw.close();
            jsObj.put("msg", msg);
            
            response.setContentType("text/html; charset=iso-8859-1");
            response.getWriter().write(jsObj.toString());
            response.getWriter().flush();
        }
        catch(Exception exx) {
            //do nothing
        }
    }
    
    protected String getLogFile(final HttpServletRequest request) {
        return null;//"C:/namthanh.sql";
    }
    
    protected boolean useConnection() {
        return false;
    }
    
    protected String getModPK() {
        return (String)getServletContext().getAttribute("MOD_PK");
    }
    
    protected String getString(final JSONObject jsObj, final String key) throws Exception {
        return (jsObj.has(key) ? jsObj.getString(key) : null);
    }
    
    protected void writeToResponse(final HttpServletResponse response, final String str) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().write(str);
        response.getWriter().flush();
    }
    
    public MessageResources getResources() {
        return (MessageResources) getServletContext().getAttribute("org.apache.struts.action.MESSAGE");
    }
    
    public String getMessage(final HttpServletRequest request, final String _strKey) {
        return getMessage(request.getSession(),_strKey);
    }
    
    protected String getMessage(final HttpSession session, final String _strKey) {
        return getResources().getMessage((java.util.Locale)session.getAttribute(org.apache.struts.action.Action.LOCALE_KEY),_strKey);
    }
    
    protected void showAllParameters(final HttpServletRequest request) {
        System.out.println("========================");
        final java.util.Enumeration e = request.getParameterNames();
        while(e.hasMoreElements()) {
            final String key = (String) e.nextElement();
            System.out.println(key + "=" + request.getParameter(key));
        }
    }

    @Override
    public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    public void jspInit() {
    }

    @Override
    public void jspDestroy() {
    }
    
    public void _jspInit() {
    }
    
    @Override
    public final void destroy() {
        super.destroy();
        jspDestroy();
    }
}
